package com.ifast.common.base;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ifast.common.utils.FileUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.jxls.area.Area;
import org.jxls.builder.AreaBuilder;
import org.jxls.builder.xls.XlsCommentAreaBuilder;
import org.jxls.common.CellRef;
import org.jxls.common.Context;
import org.jxls.expression.JexlExpressionEvaluator;
import org.jxls.transform.Transformer;
import org.jxls.transform.poi.PoiTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.ResourceUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * 通用业务层实现
 * </pre>
 *
 * <small> 2018年1月9日 | Aron</small>
 *
 * @param <M>
 *            mapper
 * @param <T>
 *            entity
 */
public abstract class CoreServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> implements CoreService<T> {

    public Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public List<T> findByKv(Object... params) {
        if (params == null) {
            return new ArrayList<>();
        }
        return baseMapper.selectByMap(convertToMap(params));
    }

    @Override
    public T findOneByKv(Object... params) {
        return selectOne(this.convertToEntityWrapper(params));
    }

    @Override
    public Map<String, Object> convertToMap(Object... params) {
        Map<String, Object> map = new HashMap<>();
        if (params == null) {
            return map;
        }
        for (int i = 0; i < params.length; i++) {
            if (i % 2 == 1) {
                map.put((String) params[i - 1], params[i]);
            }
        }
        return map;
    }
    @Override
    public EntityWrapper<T> convertToEntityWrapper(Object... params) {
        EntityWrapper<T> ew = new EntityWrapper<>();
        if (params == null) {
            return ew;
        }
        for (int i = 0; i < params.length; i++) {
            if (i % 2 == 1) {
                ew.eq((String) params[i - 1], params[i]);
            }
        }
        return ew;
    }

    public void excelExport(String importModelName, List<?> results, HttpServletResponse response, String exportFileName) {
        this.excelExport(importModelName,results,null,response,exportFileName);
    }




    public void excelExport(String importModelName, List<?> results, Map<String, Object> heads, HttpServletResponse response, String exportFileName) {
        InputStream istream = null;
        ServletOutputStream os = null;
//      OutputStream os = null;
        try {
            File modelFile = FileUtil.fetchExcelModelFile(importModelName);

//          istream = new FileInputStream("f:\\jj_basicinfo.xls");

            istream = new FileInputStream(modelFile);

            Workbook workbook = WorkbookFactory.create(istream);
            Transformer transformer = PoiTransformer.createTransformer(workbook);
//          Transformer transformer = PoiTransformer.createSxssfTransformer(workbook, 100, false);

			/* 解决:org.jxls.expression.JexlExpressionEvaluator.evaluate@61![0,4]: ‘aaaa;‘ undefined variable aaaa */
            //获取配置
            JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator)transformer.getTransformationConfig().getExpressionEvaluator();
            evaluator.getJexlEngine().setSilent(true); //设置静默模式，不报警告

            AreaBuilder areaBuilder = new XlsCommentAreaBuilder(transformer);
            List<Area> xlsAreaList = areaBuilder.build();
            Area xlsArea = xlsAreaList.get(0);

            Context context = null;
            if (heads != null && !heads.isEmpty()) {
                context = new Context(heads);
            } else {
                context = new Context();
            }
            context.putVar("rows",results);

            context.getConfig().setIsFormulaProcessingRequired(false); // with SXSSF you cannot use normal formula processing

            xlsArea.applyAt(new CellRef("result!A1"), context);
            // 从模板中获得设置的sheet名
            String sheetName = workbook.getSheetName(0);
            //删除第一个Sheet中的模信息，并以Sheet名为输出Sheet名称
            workbook.removeSheetAt(0);
            workbook.setSheetName(0,sheetName);

            workbook.setForceFormulaRecalculation(true);
            workbook.setActiveSheet(0);

            response.setContentType("application/xls");
            response.setHeader("Content-Disposition", "attachment; filename=" + exportFileName + FileUtil.TYPE_EXCEL_MODEL);
            os = response.getOutputStream();


//          os = new FileOutputStream("f:/target/simple_sxssf_output333.xlsx");

            ((PoiTransformer) transformer).getWorkbook().write(os);
            os.flush();
        }catch(Exception e) {
            e.printStackTrace();
            //TODO
        }finally {
            try {
                if(os != null ) os.close();
                if(istream != null) istream.close();
            }catch (IOException e){
                //TODO
            }
        }

    }

}
